package com.syqc.monitor.ui.cost

import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.syqc.choose.car.ChooseCarActivity
import com.syqc.choose.teamcar.TeamsCarsActivity
import com.syqc.comlib.base.BaseBarActivity
import com.syqc.comlib.custom.timer.CustomDatePicker
import com.syqc.comlib.custom.timer.DateFormatUtils
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityOilAddBinding
import com.syqc.monitor.databinding.IncludeRecyclerWrapBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.TimeUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

class OilFeeActivity : BaseBarActivity<ActivityOilAddBinding>(ActivityOilAddBinding::inflate) {
    private lateinit var mSureVB: IncludeSelectSureBinding
    private lateinit var mRecyclerVB: IncludeRecyclerWrapBinding
    private val mViewModel by viewModels<OilFeeViewModel>()

    private val mAdapter by lazy { PhotoAdapter() }

    private val mUploadPopup by lazy {
        UploadPopup(this) {
            if (it) {
                mViewModel.clearData()
            } else {
                mViewModel.update()
            }
        }
    }

    override fun initView() {
        ToolbarHelper.setToolbar(this, intent.getStringExtra(Keys.INTENT_TITLE) ?: "")
        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        mRecyclerVB = IncludeRecyclerWrapBinding.bind(binding.root)
        mSureVB.tvSure.setText(R.string.desc_com_sure)
        mViewModel.initData()
        binding.tvFeeUpDate.text = mViewModel.upDate

        mRecyclerVB.recyclerWrap.layoutManager = GridLayoutManager(this, 3)
        mRecyclerVB.recyclerWrap.adapter = mAdapter
        initViewModel()
    }

    override fun setListener() {
        binding.llFeeChoosePlate.filterFast {

            if (NetDataUtil.isSyncTree){
                launcher.launchAct<TeamsCarsActivity>(this)
            }else{
                launcher.launchAct<ChooseCarActivity>(this)
            }
        }

        mSureVB.tvSure.filterFast {
            mViewModel.upOilFee()
        }

        binding.llFeeUpDate.filterFast {
            mDatePicker.show(mViewModel.upDate)
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            mViewModel.photoIndex = position
            val path = mAdapter.data[position]
            if (path.isEmpty()) {
                val selectionModel = PictureSelector.create(this@OilFeeActivity)
                    .openCamera(SelectMimeType.ofImage())
                selectionModel.forResult(callbackListener)
            }
        }

        mAdapter.setOnItemChildClickListener { _, _, position ->
            mAdapter.data[position] = ""
            mAdapter.notifyItemChanged(position)
            mViewModel.removeIndexPhoto(position)
        }
    }

    fun initViewModel() {
        mViewModel.toastObserver().subscribeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(this::toastObserver)
        //提交结果监听
        mViewModel.resultLive.observe(this) {
            mUploadPopup.show(window.decorView, it)
        }

        mViewModel.photoOilLive.observe(this) {
            mAdapter.setList(it)
        }
    }


    private val launcher = registerResultOk { result ->
        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME)
            binding.tvFeeChoosePlate.text = carName
            mViewModel.carId = carId
        }
    }


    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this,
            callback,
            TimeUtil.simpleDate,
            TimeUtil.instance.simpleTime(System.currentTimeMillis()),
            false
        ).apply {
            setCanShowPreciseTime(false)
        }
    }

    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            val time: String = DateFormatUtils.long2Str(timestamp, false)
            binding.tvFeeUpDate.text = time
            mViewModel.upDate = time
            mDatePicker.dismiss()
        }
    }


    private val callbackListener = object : OnResultCallbackListener<LocalMedia> {
        override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
            mViewModel.handlePhoto(result)
        }

        override fun onCancel() {

        }

    }

}

